<template>
  <div id="LessorsRegister">
    <el-select v-model="value" placeholder="切换登录">
      <el-option
        v-for="item in options"
        :key="item.value"
        :label="item.label"
        :value="item.value"
        :disabled="item.disabled"
      >
      </el-option>
    </el-select>

    <h1>lessorsRegister</h1>
    <el-form
      :model="ruleForm"
      status-icon
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-form-item label="用户名" prop="age">
        <el-input
          v-model="ruleForm.age"
          placeholder="2-11位只含有汉字、数字、字母、下划线不能以下划线开头和结尾"
          @blur="isAccess"
        ></el-input>
      </el-form-item>

      <el-form-item label="手机号" prop="phoneNumber">
        <el-input
          v-model="ruleForm.phoneNumber"
          placeholder="请输入以1开头第二位是3-9的11位手机号"
        ></el-input>
      </el-form-item>

      <el-form-item label="密码" prop="pass">
        <el-input
          type="password"
          v-model="ruleForm.pass"
          autocomplete="off"
          placeholder="6~16位大写字母开头只包含大小写字母和数字"
        ></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="checkPass">
        <el-input
          type="password"
          v-model="ruleForm.checkPass"
          autocomplete="off"
          placeholder="两次输入密码保持一致"
          @blur="isSubmit"
        ></el-input>
      </el-form-item>
      <!-- 上传头像 -->
      <el-form-item label="上传头像" prop="checkPass">
        <el-upload
          class="avatar-uploader"
          action="http://localhost:3000/images/upload"
          :show-file-list="false"
          :on-success="handleSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img
            v-if="imagesName"
            :src="'http://localhost:3000/temp/' + imagesName"
            class="avatar"
          />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>

      <!-- 提交按钮 -->
      <el-form-item>
        <template>
          <el-button type="primary" @click="submitForm('ruleForm')" v-if="state"
            >提交</el-button
          >
          <el-button type="warning" disabled v-if="!state">提交</el-button>
        </template>

        <el-button type="primary" @click="$router.push('/LessorsLogin')"
          >立即登录</el-button
        >
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import axios from "axios";
const accountTest = /^(?!_)(?!.*?_$)[a-zA-Z0-9_\u4e00-\u9fa5]{2,11}$/;
export default {
  data() {
    //用户名 原本是要手机号或者邮箱 满足条件才行,现在是切换到随意的不为空的用户名
    //再改成用户名有验证的
    var checkAge = (rule, value, callback) => {
      // let phone = /^1[3-9]\d{9}$/;
      // let email = /^[^0-9]\S*@[0-9A-Za-z]{2,3}.[A-Za-z]{2,4}$/;
      const account = this.ruleForm.age;
      // const isfalse = !(phone.test(account) || email.test(account));
      const accountTest = /^(?!_)(?!.*?_$)[a-zA-Z0-9_\u4e00-\u9fa5]{2,11}$/;
      const isfalse = !accountTest.test(account);
      if (!value) {
        this.state = false;
        return callback(new Error("用户名不能为空"));
      }
      setTimeout(() => {
        if (isfalse) {
          callback(
            new Error(
              "2-11位只含有汉字、数字、字母、下划线不能以下划线开头和结尾"
            )
          );
          this.state = false;
        } else {
          callback();
          this.isSubmit();
        }
      }, 100);
    };
    //手机号验证
    var checkPhone = (rule, value, callback) => {
      let phone = /^1[3-9]\d{9}$/;
      const phoneNumber = this.ruleForm.phoneNumber;
      const isfalse = !phone.test(phoneNumber);
      if (!value) {
        this.state = false;
        return callback(new Error("手机号不能为空"));
      }
      setTimeout(() => {
        if (isfalse) {
          callback(new Error("必须以1开头第二位是3-9的11位手机号"));
          this.state = false;
        } else {
          callback();
          this.isSubmit();
        }
      }, 100);
    };
    //密码验证满足正则条件
    var validatePass = (rule, value, callback) => {
      let pwd = /^[A-Z][a-zA-Z0-9]{5,15}$/;
      const password = this.ruleForm.pass;
      const isfalse = !pwd.test(password);
      if (value === "" || isfalse) {
        callback(new Error("6~16位大写字母开头只包含大小写字母和数字"));
        this.isSubmit();
      } else {
        if (this.ruleForm.checkPass !== "") {
          this.$refs.ruleForm.validateField("checkPass");
        }
        callback();
        this.isSubmit();
      }
    };
    //二次密码验证
    var validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
        this.isSubmit();
      } else if (value !== this.ruleForm.pass) {
        callback(new Error("两次输入密码不一致!"));
        this.isSubmit();
      } else {
        callback();
        this.isSubmit();
      }
    };
    return {
      state: false,
      ruleForm: {
        pass: "",
        checkPass: "",
        age: "",
        phoneNumber: "",
      },
      rules: {
        pass: [{ validator: validatePass, trigger: "blur" }],
        checkPass: [{ validator: validatePass2, trigger: "blur" }],
        age: [{ validator: checkAge, trigger: "blur" }],
        phoneNumber: [{ validator: checkPhone, trigger: "blur" }],
      },
      // 和登录介绍一样 切换租户 出租方 管理员 登录页面的
      options: [
        {
          value: "/customer",
          label: "租户",
        },
        {
          value: "/lessorsLogin",
          label: "出租方登录",
        },
        {
          value: "/lessorsRegister",
          label: "出租方注册",
          disabled: true,
        },
        {
          value: "/adminsLogin",
          label: "管理员",
        },
      ],
      value: "",
      // 上传图片地址
      imagesName: "",
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          //发送 axios 请求
          this.lessorsRegister();
          //避免重复点击提交,清空注册栏的内容
          const account = (this.ruleForm.age = "");
          const password = (this.ruleForm.pass = "");
          const phone = (this.ruleForm.phoneNumber = "");
          const checkPass = (this.ruleForm.checkPass = "");
          // alert("注册成功");
          this.open2("恭喜注册成功", "success");
        } else {
          //一般不会触发这个条件
          console.log("error submit!!");
          return false;
        }
      });
    },
    //重置按钮
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.imagesName = "";
    },
    //失焦验证用户名是否存在
    async isAccess() {
      // let phone = /^1[3-9]\d{9}$/;
      const account = this.ruleForm.age;
      if (accountTest.test(account)) {
        // alert("输入用户名满足格式要求");
        const msg = await axios({
          url: "http://localhost:3000/lessors/isAccess",
          method: "post",
          data: { account },
        });
        if (msg.data.status) {
          // alert("输入用户名满足注册条件");
          this.isSubmit();
        } else {
          // alert("输入用户名已存在请重新输入");
          this.open2("用户名已存在请重新输入", "warning");

          this.state = false;
          //输入用户名存在所以输入框用户名为空字符串
          this.ruleForm.age = "";
        }
      } else {
        // alert("请输入以1开头第二位是3-9的11位手机号");
        this.open2("请输入正确格式用户名", "warning");

        this.state = false;
      }
    },
    // 图片上传成功获取图片路径的方法
    handleSuccess(response) {
      if (response.status) {
        this.imagesName = response.data;
        this.isSubmit();
      }
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },

    //二次输入密码失焦验证提交按钮能不能点击
    isSubmit() {
      const account = this.ruleForm.age;
      const phoneNumber = this.ruleForm.phoneNumber;
      const password = this.ruleForm.pass;
      const secondPass = this.ruleForm.checkPass;
      let phone = /^1[3-9]\d{9}$/;
      let pwd = /^[A-Z][a-zA-Z0-9]{5,15}$/;
      let email = /^[^0-9]\S*@[0-9A-Za-z]{2,3}.[A-Za-z]{2,4}$/;
      // const istrue = phone.test(account) || email.test(account);
      const istrue = accountTest.test(account);
      if (
        istrue &&
        pwd.test(password) &&
        password == secondPass &&
        phone.test(phoneNumber) &&
        this.imagesName
      ) {
        this.state = true;
      } else {
        this.state = false;
      }
    },

    //点击注册
    async lessorsRegister() {
      const account = this.ruleForm.age;
      const password = this.ruleForm.pass;
      const phone = this.ruleForm.phoneNumber;
      // console.log(account, password, phone);
      const data = await axios({
        url: "http://localhost:3000/lessors/register",
        method: "post",
        data: {
          account,
          password,
          phone,
          imagesName: this.imagesName,
        },
      });
    },
    // 提示框  style的值不同触发不同的提示框: 'success','warning',
    open2(msg, style) {
      this.$message({
        message: msg, //    例如: 传入 '恭喜你，这是一条成功消息',
        type: style,
      });
    },
  },
  // 监听value的变换切换到 设置的路由页面去
  watch: {
    value(newValue) {
      this.$router.push(newValue);
    },
  },
};
</script>

<style>
#LessorsRegister h1 {
  color: #409eff;
  margin-bottom: 30px;
}
#LessorsRegister {
  width: 500px;
  margin: 30px auto;
  text-align: center;
}
/* 设置注册前面的 * 星号 */
#LessorsRegister .el-form-item__label:before {
  content: "*";
  color: #f56c6c;
  margin-right: 4px;
}
#LessorsRegister .el-select {
  width: 110px;
  left: 195px;
}
/* 上传图片样式 */
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>